from mydefine import *
import requests
import yaml

def download(head_recved, db):
    # 查找模型数量与下载次数
    status, [(md_count, dl_count)] = db.sqlexe(f'SELECT count1, download FROM tb_info WHERE assetType=="{ASSET_MODEL}"')
    if status != None:
        return {"type": RESPONSE_ERROR, "status": status}
    
    # 查询类型数量
    status, rows = db.sqlexe(f'select name from tb_type where assetType="{ASSET_MODEL}"')
    if status != None:
        return {"type": RESPONSE_ERROR, "status": status}
    type_count = len(rows)

    if head_recved['is_query'] is False:
        # 下载次数加一
        dl_count += 1
        status, _ = db.sqlexe(f'update tb_info set download={dl_count} where assetType="{ASSET_MODEL}"')
        if (None != status):
            return {"type": RESPONSE_ERROR, "status": status}
    
    print(f'模型数量: {md_count}, 类型数量: {type_count}, 下载次数: {dl_count}')

    with open('config.yml', 'r') as conf_file:
        ymlConf = yaml.load(conf_file, Loader= yaml.FullLoader)
        interfaceConf = ymlConf['interface']
        url = interfaceConf['interface-url']
        id_dl_count     = str(interfaceConf['id_dl_count'])
        id_md_count     = str(interfaceConf['id_md_count'])
        id_type_count   = str(interfaceConf['id_type_count'])
        print(f'interface url: {url}')
        
    data = [
        {
            "id": id_dl_count,  # 三维模型库中模型下载次数
            "value": dl_count
        },
        {
            "id": id_md_count,  # 三维模型库中模型总数量
            "value": md_count
        },
        {
            "id": id_type_count,  # 平台检索三维模型的类型数量
            "value": type_count
        }
    ]
    try:
        print(f'ready to send: {data}')
        resp = requests.post(url=url, json=data)
        print(f'HTTP Server Response: {resp.text}')
    except:
        print("接口HTTP服务器错误")
        return {"type": RESPONSE_DOWNLOAD, "status": "接口HTTP服务器错误"}

    return {"type": RESPONSE_DOWNLOAD, "status": "", "models": {}}
